package com.zzb.controller;

import com.zzb.DTO.ImgDTO;
import com.zzb.DTO.ResultDTO;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * @author ASUS
 */
@RestController
@CrossOrigin
public class UploadController {

    /**
     * 上传文件存储目录
     */
    private static final String UPLOAD_DIRECTORY = "upload";
    @PostMapping("/upload")
    public ResultDTO fileUpload(MultipartFile file, HttpServletRequest request){
        if (file != null && !file.isEmpty()) {
            //获取文件路径
            String uploadPath = request.getServletContext().getRealPath("");
            //文件本地保存路径
            String path = uploadPath.split("out")[0] + "/web/" + UPLOAD_DIRECTORY;
            //文件命名
            String fileName = System.currentTimeMillis() + "--" + file.getOriginalFilename();
            try {
                //获取文件输入流
                InputStream inputStream = file.getInputStream();

                //存入out文件中
                //copyFile(inputStream,uploadPath,fileName);

                //存入本地文件中
                copyFile(inputStream,path,fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ResultDTO.getResult("success",1,new ImgDTO("/period/web/"+UPLOAD_DIRECTORY+"/"+fileName));
        }
        return ResultDTO.getResult("error");
    }

    /**
     * 创建文件夹
     * @param uploadPath 文件夹路径
     */
    private void createDirectory(String uploadPath) {
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
    }

    /**
     * 文件复制
     * @param inputStream 文件输入流
     * @param uploadPath 文件夹路径
     * @param fileName 文件名称
     */
    private void copyFile(InputStream inputStream, String uploadPath, String fileName){
        String newPath=uploadPath + "/" +fileName;
        createDirectory(uploadPath);
        try {
            OutputStream outputStream = new FileOutputStream(newPath);
            createDirectory(newPath);
            IOUtils.copy(inputStream,outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
